<template>
    <div>
        MQTT {{ messageState.message }}
    </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { Client, Message } from "paho-mqtt";


// 创建 MQTT 客户端实例
const client = new Client("ws://192.168.3.11:8083/mqtt", "data-proxy");

// 创建响应式数据
const messageState = reactive<any>({ message: {} });

// MQTT 连接成功时的回调函数
client.onConnectionLost = (responseObject: any) => {
    if (responseObject.errorCode !== 0) {
        console.log("连接丢失: " + responseObject.errorMessage);
    }
};

// 订阅主题成功时的回调函数
client.onMessageArrived = (message: any) => {
    console.log("接收到消息: -------------- " + JSON.parse(message.payloadString), typeof (JSON.parse(message.payloadString)));
    // 处理收到的消息
    messageState.message = JSON.parse(message.payloadString)
    //     message = JSON.parse(message.payloadString)
    //     console.log('message', message)
};

// 连接到 MQTT 服务器
client.connect({
    onSuccess: () => {
        console.log("已连接到 MQTT 服务器");
        // 订阅主题
        client.subscribe("index", { qos: 1 });
    },
    onFailure: (error: any) => {
        console.log("连接失败: " + error.errorMessage);
    },

});


</script>